<template>
  <ZButton @click="show = true">
    <template #icon>
      <span class="icon-[uil--search] h-6 w-6"></span>
    </template>
    <span class="hidden sm:inline">搜索...</span>
    <div class="hidden lg:block">
      <kbd class="kbd">{{ os === "MacOS" ? "⌘" : "Ctrl" }}</kbd>
      <kbd class="kbd">K</kbd>
    </div>
  </ZButton>
  <Teleport to="body">
    <ZDialog
      v-model="show"
      box-class="h-[80%] max-w-[80%] lg:max-w-[60%] shadow-lg shadow-primary/40 flex flex-col justify-between"
    >
      <ZInput class="input-primary mb-4 w-full" v-model="searchText" />
      <h3 class="font-medium text-primary">搜索结果</h3>
      <div class="my-4 flex-1">
        <div v-if="data?.success" class="max-h-96 overflow-auto">
          <div
            class="my-2 flex gap-4 rounded-md border border-primary p-2 shadow-md hover:shadow-primary/20"
            :class="{
              'bg-primary text-primary-content': idx === selectIndex,
            }"
            v-for="(post, idx) in posts"
            :key="post.id"
            @click="go(idx)"
          >
            <div
              class="hidden aspect-video w-24 overflow-hidden rounded-md sm:block"
            >
              <img
                class="h-full w-full cursor-pointer object-cover"
                :src="post.cover"
                alt="pos"
              />
            </div>
            <div class="flex-1 overflow-hidden">
              <a class="cursor-pointer">
                <div class="line-clamp-1 flex items-center">
                  <h3 class="mr-4 max-w-[65%] truncate text-xl">
                    {{ post.title }}
                  </h3>
                  <div class="line-clamp-1 max-w-[35%] text-sm">
                    作者:{{ post.nickname }}
                  </div>
                </div>
                <p class="truncate text-sm">
                  {{ post.digest }}
                </p>
              </a>
            </div>
          </div>
        </div>
      </div>
      <div>
        <ul class="hidden gap-4 md:flex">
          <li class="flex items-center gap-2">
            <kbd class="kbd kbd-sm"
              ><span class="icon-[uil--enter]"></span
            ></kbd>
            <span>回车选择</span>
          </li>
          <li class="flex items-center gap-2">
            <kbd class="kbd kbd-sm"
              ><span class="icon-[uil--arrow-up]"></span
            ></kbd>
            <kbd class="kbd kbd-sm"
              ><span class="icon-[uil--arrow-down]"></span
            ></kbd>
            <span>上下键导航</span>
          </li>
          <li class="flex items-center gap-2">
            <kbd class="kbd kbd-sm">ESC</kbd>
            <span>关闭对话框</span>
          </li>
        </ul>
      </div>
    </ZDialog>
  </Teleport>
</template>
<script setup lang="ts">
import type { Post } from "@/stores/types";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";
import { getOs } from "./utils";

interface Props {
  pathName: string;
  queryUrl: string;
}
const props = defineProps<Props>();

const os = getOs(),
  show = ref(false),
  selectIndex = ref(-1);

const router = useRouter();
const go = (index?: number) => {
  if (index !== undefined) {
    selectIndex.value = index;
  }
  if (show.value && selectIndex.value >= 0) {
    router.push({
      name: props.pathName,
      params: {
        id: posts.value[selectIndex.value].id,
      },
    });
    show.value = false;
  }
};
// key bind
const { Meta_K, Ctrl_K, Enter, Up, Down } = useMagicKeys();
const hotKey = os == "MacOS" ? Meta_K : Ctrl_K;
watch(hotKey, (value) => {
  if (value) {
    show.value = true;
  }
});

watch(Enter, (value) => {
  if (show.value && value) {
    go();
  }
});
watch(Up, (value) => {
  if (show.value && value && selectIndex.value > 0) {
    selectIndex.value -= 1;
  }
});
watch(Down, (value) => {
  if (show.value && value && selectIndex.value < posts.value.length - 1) {
    selectIndex.value += 1;
  }
});

// search
const searchText = ref("");

const url = computed(() => `${props.queryUrl}=${searchText.value}`);
const { data, onFetchResponse } = useApiFetch(url, {
  refetch: true,
  immediate: false,
}).json<ApiResponse<Post & { nickname: string }>>();

const posts = computed(() => data.value?.query.results || []);
watch(posts, () => {
  console.log("posts", posts.value);
});

onFetchResponse(() => {
  if (data.value?.success) {
    selectIndex.value = posts.value.length > 0 ? 0 : -1;
  }
});
</script>
